use log;
use colour::*;
use log::*;
use toml::*;
use std::fs;
use grapeTimerR::{timer, IDMode};
use simple_log::LogConfigBuilder;
use crate::config::AppConfig;
use crate::action_factory::spawn_action;

// 引入本地行为
mod action_factory;
mod action_http;
mod action_tcp;
mod runtime;
mod config;
mod error;
mod action_ping;
mod action_ws;
mod action_do;


fn main() {
    blue_ln!("  _   _      _     ____ _                _             ____            _   ");
    blue_ln!(" | |_(_) ___| | __/ ___| |__   __ _  ___| | _____ _ __|  _ \\ _   _ ___| |_ ");
    blue_ln!(" | __| |/ __| |/ / |   | '_ \\ / _` |/ __| |/ / _ \\ '__| |_) | | | / __| __|");
    blue_ln!(" | |_| | (__|   <| |___| | | | (_| | (__|   <  __/ |  |  _ <| |_| \\__ \\ |_ ");
    blue_ln!("  \\__|_|\\___|_|\\_\\\\____|_| |_|\\__,_|\\___|_|\\_\\___|_|  |_| \\_\\\\__,_|___/\\__| tickChecker for Rust");
    green_ln!("==== Version 1.0.0 ===========================================================");

    let mut glob_config = AppConfig{
        log_path: String::new(),
        log_level: String::new(),
        roll_count: 0,
        file_size: 0,
        timer_debug: false,
        timer_log: String::new(),
        work_thread: 0,
        action: vec![]
    };

    let r = fs::read_to_string("./config/app.toml");
    match r {
        Ok(toml_data) => {
            let sconf:AppConfig = toml::from_str(toml_data.as_str()).unwrap();
            glob_config = sconf;
        },
        Err(e) => {
            error!("load config faild: {}",e);
            println!("load config faild: {}",e);
            return;
        }
    }

    let config = LogConfigBuilder::builder()
        .path(glob_config.log_path.as_str())
        .size(glob_config.file_size as u64)
        .roll_count(glob_config.roll_count as u32)
        .level(glob_config.log_level)
        .output_file()
        .output_console()
        .build();

    simple_log::new(config).unwrap();

    info!("start init timer...");
    let timer_conf = timer::Config{
        debug: glob_config.timer_debug,
        debug_log: glob_config.timer_log,
        thread_count: glob_config.work_thread,
        id_seed: 100,
        id_type: IDMode::TimestampId
    };

    timer::init_schedule(timer_conf);

    info!("action count:{}",glob_config.action.len());
    info!("start build actions...");

    for appCnf in glob_config.action {
        spawn_action(&appCnf);
    }

    // 开启
    info!("start tick all task...");
    timer::wait_forever();
}
